
/**
 * ArrayBuffer转为临时URL链接
 * @param {ArrayBuffer} data 文件ArrayBuffer
 * @param {String} type 文件类型
 * @returns 
 */
export function arrayBufferToURL(data, type) {
    const blob = new Blob([data], { type: type });
    const urlCreator = window.URL || window.webkitURL;
    return urlCreator.createObjectURL(blob);
}

/**
 * ArrayBuffer转为Base64
 * @param {ArrayBuffer} data 文件ArrayBuffer
 * @returns 
 */
export function arrayBufferToBase64(data) {
    const bytes = new Uint8Array(data);
    let binary = '';
    for (let i = 0; i < bytes.byteLength; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}

/**
 * Base64转为ArrayBuffer
 * @param {String} data Base64字符串
 * @returns 
 */
export function base64ToArrayBuffer(data) {
    const binaryString = atob(data);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

/**
 * File转ArrayBuffer
 * @param {File} file 文件
 * @returns 
 */
export function readFileAsArrayBuffer(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    });
}